package com.kancy.springcloudconfig.action;

import com.kancy.springcloudconfig.action.model.AlgorithmData;
import com.kancy.springcloudconfig.action.model.RefreshObject;
import com.kancy.springcloudconfig.constants.Constants;
import com.kancy.springcloudconfig.exception.AlertException;
import com.kancy.springcloudconfig.util.AESUtil;
import com.kancy.springcloudconfig.util.CommonUtil;

import java.util.Objects;

/**
 * <p>
 * CipherAlgorithAction
 * </p>
 *
 * @author: kancy
 * @date: 2019/10/26 14:09
 **/
public class AesAlgorithAction extends AbstractAlgorithmAction {

    /**
     * 检查数据
     *
     * @param data
     */
    @Override
    protected void checkAlgorithmData(AlgorithmData data) {
        super.checkAlgorithmData(data);
        // 默认值
        if (CommonUtil.isEmpty(data.getPassword())){
            data.setPassword(Constants.DEFAULT_AES_PASSWORD);
        }
        if (CommonUtil.isEmpty(data.getSalt())){
            data.setSalt(Constants.DEFAULT_AES_SALT);
        }
        if (data.getPassword().trim().length() != 16){
            throw new AlertException("密钥长度必须等于十六!");
        }
        if (data.getSalt().trim().length() != 16){
            throw new AlertException("向量长度必须等于十六!");
        }
    }

    /**
     * 解密逻辑
     *
     * @param data
     */
    @Override
    protected String decrypt(AlgorithmData data) {
        AESUtil instance = AESUtil.getInstance(data.getPassword(), data.getSalt());
        String decrypt =  instance.aesDecrypt(data.getCipherText());
        if (Objects.isNull(decrypt)){
            throw new AlertException("解密失败！");
        }
        return decrypt;
    }

    /**
     * 加密逻辑
     *
     * @param data
     */
    @Override
    protected String encrypt(AlgorithmData data) {
        AESUtil instance = AESUtil.getInstance(data.getPassword(), data.getSalt());
        String encrypt = instance.aesEncrypt(data.getPlainText());
        if (Objects.isNull(encrypt)){
            throw new AlertException("加密失败！");
        }
        return encrypt;
    }

    @Override
    protected void update(RefreshObject object) {
        object.getPasswordObject().setVisible(true);
        object.getPasswordObject().setText(Constants.DEFAULT_AES_PASSWORD);
        object.getSaltObject().setVisible(true);
        object.getSaltObject().setText(Constants.DEFAULT_AES_SALT);

        object.getLabel1Object().setVisible(true);
        object.getLabel1Object().setText("密钥:");
        object.getLabel2Object().setVisible(true);
        object.getLabel2Object().setText("向量:");
    }
}
